﻿using System;
using System.Web;
using System.Data;

namespace msBsc.WebUi
{
    public partial class wfShopLogistics : msBsc.Cls.BPDealer
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindControls(); 
            }

        }
        private void BindControls()
        {
            if (!IsPostBack)
            {
                BoundTempNme("");
                doZoneListSet("", strCurrTempId);
            }
        }

        private string strCurrTempId = "";
        private void BoundTempNme(string strTempId)
        {
            using (msBsc.AppLogic.DataAlc.CBizShpCommercialLogistics oCDbAccess = new msBsc.AppLogic.DataAlc.CBizShpCommercialLogistics())
            { 

                DataSet ds = oCDbAccess.SelectTempNmeByDealerId(msBsc.SvRef.UserInfo.OperDealerId.Split(',')[0]);
                this.BoundComboBox("dplSelectTemplate", ds, "TEMPLATE_NME", "LOGISTICS_TEMPLATE_ID", "", "", false);
                if (strTempId == string.Empty && ds.Tables[0].Rows.Count > 0 || strTempId != string.Empty && ds.Tables[0].Rows.Count > 0 && ds.Tables[0].Select("LOGISTICS_TEMPLATE_ID='" + strTempId + "'").Length <= 0)
                {
                    strTempId = ds.Tables[0].Rows[0]["LOGISTICS_TEMPLATE_ID"].ToString();
                }
                this.SetContrlValue("dplSelectTemplate", strTempId);
                strCurrTempId = strTempId;
                loadlist(strTempId);
            }
        } 

        private void loadlist(string strTempId)
        {
            using (msBsc.AppLogic.DataAlc.CBizShpCommercialLogistics odataobj = new AppLogic.DataAlc.CBizShpCommercialLogistics())
            {
                DataSet ds = odataobj.DataObj.QueryBySQL(@"
    SELECT
    B.ZONE_TITLE
    ,ZONE_DESC=dbo.strJoin(B.ZONE_DESC)
    ,B.QTY_FIRST
    ,B.PRICE_FIRST
    ,B.QTY_ADD
    ,B.PRICE_ADD
    FROM SHP_COMMERCIAL_LOGISTICS_ZONE B
    WHERE 
    B.COMM_TENANT_ID='" + msBsc.SvRef.UserInfo.OperDealerId.Split(',')[0] + @"'
    AND B.LOGISTICS_TEMPLATE_ID='" + strTempId + @"'
    GROUP BY
    B.ZONE_TITLE
    ,B.QTY_FIRST
    ,B.PRICE_FIRST
    ,B.QTY_ADD
    ,B.PRICE_ADD
    ");



                //DataSet ds = odataobj.SelectByDealerId(msBsc.SvRef.UserInfo.OperDealerId.Split(',')[0], strTempNme);

                string strjsontem1 = msBsc.AppLogic.Cfg.HttpTools.GetJsonByTable(ds.Tables[0], "", "", 1, 1000, "");
                this.ExecJScript(@" var data = " + strjsontem1 + @";
                                    var tpl =HtmlUtil.htmlDecode(document.getElementById('list_temp').innerHTML);  
                                    laytpl(tpl).render(data, function(render){
                                        document.getElementById('loadlist').innerHTML = render;
                                    });
                "); 
            }
        }

        private void doedit(string strtempid,string strzonetitle)
        {
            using (msBsc.AppLogic.DataAlc.CBizShpCommercialLogistics odataobj = new AppLogic.DataAlc.CBizShpCommercialLogistics())
            {
                DataSet ds = odataobj.DataObj.QueryBySQL(@"
    SELECT TOP 1 
    B.ZONE_TITLE 
    ,B.QTY_FIRST
    ,B.PRICE_FIRST
    ,B.QTY_ADD
    ,B.PRICE_ADD
    FROM SHP_COMMERCIAL_LOGISTICS_ZONE B
    WHERE 
    B.COMM_TENANT_ID='" + msBsc.SvRef.UserInfo.OperDealerId.Split(',')[0] + @"'
    AND B.LOGISTICS_TEMPLATE_ID='" + strtempid + @"'
    AND B.ZONE_TITLE='" + strzonetitle + @"' 
    ");
                if (ds.Tables[0].Rows.Count > 0)
                {
                    SetContrlValue("txtZoneTitle", ds.Tables[0].Rows[0]["ZONE_TITLE"].ToString());
                    SetContrlValue("txtZONE_TITLE", ds.Tables[0].Rows[0]["ZONE_TITLE"].ToString());
                    SetContrlValue("txtQTY_FIRST", ds.Tables[0].Rows[0]["QTY_FIRST"].ToString());
                    SetContrlValue("txtPRICE_FIRST", ds.Tables[0].Rows[0]["PRICE_FIRST"].ToString());
                    SetContrlValue("txtQTY_ADD", ds.Tables[0].Rows[0]["QTY_ADD"].ToString());
                    SetContrlValue("txtPRICE_ADD", ds.Tables[0].Rows[0]["PRICE_ADD"].ToString());
                }
            }
                    doZoneListSet(strtempid, strzonetitle); 
        }
        private void dodelete(string strLogisId, string strZoneTitle)
        {
            if (strLogisId == string.Empty || strZoneTitle==string.Empty)
            {
                return;
            }
            using (msBsc.AppLogic.DataAlc.CBizShpCommercialLogistics odataobj = new AppLogic.DataAlc.CBizShpCommercialLogistics())
            {
                odataobj.DataObj.ExecuteBySQL("DELETE BB FROM SHP_COMMERCIAL_LOGISTICS_ZONE BB  WHERE BB.COMM_TENANT_ID='" + msBsc.SvRef.UserInfo.OperDealerId.Split(',')[0] + @"' AND BB.LOGISTICS_TEMPLATE_ID='" + strLogisId + @"'   AND BB.ZONE_TITLE='" + strZoneTitle + @"' ");
                    this.ExecJScript("layer.msg('成功删除发货地址！',1,{type:1,shade:false});"); 
            }
            loadlist(strLogisId);
        }
        private void dodeleteTemp(string strLogisId)
        {
            if (strLogisId == string.Empty)
            {
                return;
            }
            System.Transactions.TransactionOptions transactionOption = new System.Transactions.TransactionOptions();
            transactionOption.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
            transactionOption.Timeout = new TimeSpan(0, 10, 0);
            using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, transactionOption))
            {
                using (msBsc.AppLogic.DataAlc.CBizShpCommercialLogistics odataobj = new AppLogic.DataAlc.CBizShpCommercialLogistics())
                {
                    odataobj.DataObj.ExecuteBySQL("DELETE BB FROM SHP_COMMERCIAL_LOGISTICS_ZONE BB  WHERE BB.COMM_TENANT_ID='" + msBsc.SvRef.UserInfo.OperDealerId.Split(',')[0] + @"' AND BB.LOGISTICS_TEMPLATE_ID='" + strLogisId + @"' ");
                    odataobj.DataObj.ExecuteBySQL("DELETE BB FROM SHP_COMMERCIAL_LOGISTICS BB  WHERE BB.COMM_TENANT_ID='" + msBsc.SvRef.UserInfo.OperDealerId.Split(',')[0] + @"' AND BB.LOGISTICS_TEMPLATE_ID='" + strLogisId + @"' ");

                }
                ts.Complete();
            }
            BoundTempNme("");
            this.ExecJScript("layer.msg('成功删除发货地址！',1,{type:1,shade:false});");
        }

        private void doZoneListSet(string strLogisId,string strZoneTitle)
        {
            using (msBsc.AppLogic.DataAlc.CBizShpCommercialLogistics odataobj = new AppLogic.DataAlc.CBizShpCommercialLogistics())
            {
                DataSet ds;
                if (strZoneTitle == string.Empty)
                {
                    ds = odataobj.DataObj.QueryBySQL(@"
    SELECT 
    A.PROVINCE_ID
    ,A.PROVINCE_NME
    ,IS_CHECKED=CAST(0 AS BIT) 
    ,ALLOW_CHECKED=CAST(CASE WHEN V1.PROVINCE_ID IS NULL THEN 1 ELSE 0 END AS BIT) 
    FROM BSE_PROVINCE A  
    LEFT OUTER JOIN
    (
    SELECT DISTINCT BB.PROVINCE_ID FROM SHP_COMMERCIAL_LOGISTICS_ZONE BB  WHERE BB.COMM_TENANT_ID='" + msBsc.SvRef.UserInfo.OperDealerId.Split(',')[0] + @"' AND BB.LOGISTICS_TEMPLATE_ID='" + strLogisId + @"' 
    ) AS V1 ON A.PROVINCE_ID=V1.PROVINCE_ID  
    ");
                }
                else
                {
                    ds = odataobj.DataObj.QueryBySQL(@"
    SELECT 
    A.PROVINCE_ID
    ,A.PROVINCE_NME
    ,IS_CHECKED=CAST(CASE WHEN B.LOGISTICS_ZONE_ID IS NULL THEN 0 ELSE 1 END AS BIT) 
    ,ALLOW_CHECKED=CAST(CASE WHEN V1.PROVINCE_ID IS NULL THEN 1 ELSE 0 END AS BIT) 
    FROM BSE_PROVINCE A 
    LEFT OUTER JOIN SHP_COMMERCIAL_LOGISTICS_ZONE B ON B.COMM_TENANT_ID='" + msBsc.SvRef.UserInfo.OperDealerId.Split(',')[0] + @"' AND B.LOGISTICS_TEMPLATE_ID='" + strLogisId + @"' AND A.PROVINCE_ID=B.PROVINCE_ID   AND B.ZONE_TITLE='" + strZoneTitle + @"'
    LEFT OUTER JOIN
    (
    SELECT DISTINCT BB.PROVINCE_ID FROM SHP_COMMERCIAL_LOGISTICS_ZONE BB  WHERE BB.COMM_TENANT_ID='" + msBsc.SvRef.UserInfo.OperDealerId.Split(',')[0] + @"' AND BB.LOGISTICS_TEMPLATE_ID='" + strLogisId + @"'   AND BB.ZONE_TITLE<>'" + strZoneTitle + @"' 
    ) AS V1 ON A.PROVINCE_ID=V1.PROVINCE_ID  
    ");
                }
                string strjsontem1 = msBsc.AppLogic.Cfg.HttpTools.GetJsonByTable(ds.Tables[0], "", "", 1, 1000, "");
                this.ExecJScript(@" var data = " + strjsontem1 + @";
                                    var tpl =HtmlUtil.htmlDecode(document.getElementById('zone_list_temp').innerHTML);  
                                    laytpl(tpl).render(data, function(render){
                                         $('#zonelistshow').empty().html(render);
                                    });
                ");


                //string strCurrentJY_LEVEL = "<samp>&gt;</samp><span>" + strJY_LEVEL1 + "</span><samp>&gt;</samp><span>" + strJY_LEVEL2 + "</span><samp>&gt;</samp><span>" + strJY_LEVEL3 + "</span></span>";
                //string strCurrentCT_LEVEL = "<samp>&gt;</samp><span>" + strCT_LEVEL1 + "</span><samp>&gt;</samp><span>" + strCT_LEVEL2 + "</span><samp>&gt;</samp><span>" + strCT_LEVEL3 + "</span></span>";

                //this.ExecJScript("$('#sys_cate_name').html('" + strCurrentJY_LEVEL + "');");
                //this.ExecJScript("$('#ct_cate_name').html('" + strCurrentCT_LEVEL + "');");
            }
        }
        
        private void doSave()
        {

            System.Transactions.TransactionOptions transactionOption = new System.Transactions.TransactionOptions();
            transactionOption.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
            transactionOption.Timeout = new TimeSpan(0, 10, 0);
            using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, transactionOption))
            {
                using (msBsc.AppLogic.DataAlc.CBizShpCommercialLogistics odataobj = new AppLogic.DataAlc.CBizShpCommercialLogistics())
                {
                    //DataSet odata;
                    //DataRow drnew;
                    //bool blNew = false;
                    //if (GetPostHtValue("LOGISTICS_TEMPLATE_ID") == string.Empty)
                    //{
                    //    odata = new Xsd.DataTds.CDmShpCommercialLogistics();
                    //    drnew = odata.Tables[0].NewRow();
                    //    drnew["LOGISTICS_TEMPLATE_ID"] = odataobj.DataObj.NewID();
                    //    drnew["COMM_TENANT_ID"] = msBsc.SvRef.UserInfo.OperDealerId.Split(',')[0];
                    //    odata.Tables[0].Rows.Add(drnew);
                    //    blNew = true;
                    //}
                    //else
                    //{
                    //    odata = odataobj.SelectById(GetPostHtValue("LOGISTICS_TEMPLATE_ID"));
                    //    if (odata.Tables[0].Rows.Count <= 0)
                    //    {
                    //        drnew = odata.Tables[0].NewRow();
                    //        drnew["LOGISTICS_TEMPLATE_ID"] = odataobj.DataObj.NewID();
                    //        drnew["COMM_TENANT_ID"] = msBsc.SvRef.UserInfo.OperDealerId.Split(',')[0];
                    //        odata.Tables[0].Rows.Add(drnew);
                    //        blNew = true;
                    //    }
                    //    else
                    //    {
                    //        drnew = odata.Tables[0].Rows[0];
                    //    }
                    //}

                    //msBsc.AppLogic.Cfg.HttpTools.CopyHashToDataRow(this.htPostDataRow, drnew,"LOGISTICS_TEMPLATE_ID");

                    //if (drnew["TEMPLATE_NME"].ToString() == string.Empty)
                    //{
                    //    Alert("请输入模版名称！");
                    //    return;
                    //}


                    string strOldZoneTitle = GetPostHtValue("OLD_ZONE_TITLE");
                    string strNewZoneTitle = GetPostHtValue("ZONE_TITLE");
                    string strTempId = GetPostHtValue("LOGISTICS_TEMPLATE_ID");

                    System.Collections.Generic.List<string> lsZoneNmes = new System.Collections.Generic.List<string>();
                    using (msBsc.AppLogic.DataAlc.CBizShpCommercialLogisticsZone oGoodsAttr = new AppLogic.DataAlc.CBizShpCommercialLogisticsZone())
                    {
                        DataSet dsGoodsAttr;
                        dsGoodsAttr = oGoodsAttr.SelectByLogisTempId(strTempId); 
                        //DataSet dsSelOthZone = oGoodsAttr.DataObj.QueryBySQL(@"SELECT BB.PROVINCE_ID FROM SHP_COMMERCIAL_LOGISTICS AA LEFT OUTER JOIN SHP_COMMERCIAL_LOGISTICS_ZONE BB ON AA.LOGISTICS_TEMPLATE_ID=BB.LOGISTICS_TEMPLATE_ID WHERE AA.COMM_TENANT_ID='" + msBsc.SvRef.UserInfo.OperDealerId.Split(',')[0] + @"' AND AA.TEMPLATE_NME='" + drnew["TEMPLATE_NME"].ToString() + @"' AND AA.LOGISTICS_TEMPLATE_ID<>'" + drnew["LOGISTICS_TEMPLATE_ID"].ToString() + @"' GROUP BY AA.TEMPLATE_NME,BB.PROVINCE_ID");

                        System.Collections.Generic.List<string> lsAttrId = new System.Collections.Generic.List<string>();
                        int iAttrCount = int.Parse(GetPostHtValue("ZONE_COUNT"));
                        for (int i = 0; i < iAttrCount; i++)
                        {
                            string strAttrId = GetPostHtValue("PROVINCE_ID" + i.ToString());
                            //if (dsGoodsAttr.Tables[0].Select("PROVINCE_ID='" + strAttrId + "'").Length > 0)
                            //{
                            //    continue;
                            //}

                            lsAttrId.Add(strAttrId);
                            lsZoneNmes.Add(GetPostHtValue("PROVINCE_NME" + i.ToString()));
                            DataRow[] arrrowtem1 = dsGoodsAttr.Tables[0].Select("PROVINCE_ID='" + strAttrId + "'");
                            DataRow drAttr;
                            if (arrrowtem1.Length > 0)
                            {
                                drAttr = arrrowtem1[0];
                            }
                            else
                            {
                                drAttr = dsGoodsAttr.Tables[0].NewRow();
                                drAttr["LOGISTICS_ZONE_ID"] = oGoodsAttr.DataObj.NewID();
                                drAttr["PROVINCE_ID"] = strAttrId;
                                drAttr["ZONE_DESC"] = GetPostHtValue("PROVINCE_NME" + i.ToString());
                                drAttr["COMM_TENANT_ID"] = msBsc.SvRef.UserInfo.OperDealerId.Split(',')[0];
                                drAttr["LOGISTICS_TEMPLATE_ID"] = strTempId;
                                dsGoodsAttr.Tables[0].Rows.Add(drAttr);
                            } 
                            drAttr["SEQ_NUM"] = i;

                            msBsc.AppLogic.Cfg.HttpTools.CopyHashToDataRow(this.htPostDataRow, drAttr, "LOGISTICS_ZONE_ID,COMM_TENANT_ID,LOGISTICS_TEMPLATE_ID,PROVINCE_ID,SEQ_NUM");
                        }

                        DataRow[] arrdelattr = dsGoodsAttr.Tables[0].Select("ZONE_TITLE='" + strOldZoneTitle + "' AND PROVINCE_ID NOT IN ('" + string.Join("','", lsAttrId.ToArray()) + "')");
                        for (int i = arrdelattr.Length - 1; i >= 0; i--)
                        {
                            arrdelattr[i].Delete();
                        }
                        oGoodsAttr.Update(dsGoodsAttr);

                    }

                    //一个模版只有一个序号0
                    odataobj.DataObj.ExecuteBySQL(@"	UPDATE A SET
	SEQ_NUM=V1.SEQ_NUM
	FROM  	
	(
		SELECT
		SEQ_NUM=ROW_NUMBER() OVER (PARTITION BY AA.LOGISTICS_TEMPLATE_ID ORDER BY AA.ZONE_TITLE ASC,AA.PROVINCE_ID ASC)-1
		,AA.LOGISTICS_ZONE_ID 
		FROM SHP_COMMERCIAL_LOGISTICS_ZONE AA
		WHERE AA.COMM_TENANT_ID='" + msBsc.SvRef.UserInfo.OperDealerId.Split(',')[0] + @"' AND AA.LOGISTICS_TEMPLATE_ID='" + strTempId + @"'   
	) AS V1 
	LEFT OUTER JOIN SHP_COMMERCIAL_LOGISTICS_ZONE A ON A.LOGISTICS_ZONE_ID=V1.LOGISTICS_ZONE_ID
");
//                    odataobj.DataObj.ExecuteBySQL(@"	UPDATE A SET
//	SEQ_NUM=V1.SEQ_NUM
//	FROM  	
//	(
//		SELECT
//		SEQ_NUM=ROW_NUMBER() OVER (PARTITION BY AA.LOGISTICS_TEMPLATE_ID ORDER BY AA.ZONE_TITLE ASC,AA.PROVINCE_ID ASC)-1
//		,AA.LOGISTICS_ZONE_ID 
//		FROM SHP_COMMERCIAL_LOGISTICS_ZONE AA
//		WHERE AA.COMM_TENANT_ID='" + msBsc.SvRef.UserInfo.OperDealerId.Split(',')[0] + @"' AND AA.LOGISTICS_TEMPLATE_ID='" + strTempId + @"' AND (ZONE_TITLE='" + strNewZoneTitle + @"' OR ZONE_TITLE='" + strOldZoneTitle + @"')
//	) AS V1 
//	LEFT OUTER JOIN SHP_COMMERCIAL_LOGISTICS_ZONE A ON A.LOGISTICS_ZONE_ID=V1.LOGISTICS_ZONE_ID
//");


                    this.ExecJScript("layer.msg('成功保存运费模版！',1,{type:1,shade:false});");
                    //BoundTempNme(drnew["TEMPLATE_NME"].ToString());
                    loadlist(strTempId);
                    ts.Complete();
                }
            }
        }

        private void doAddNewTemp()
        {
            using (msBsc.AppLogic.DataAlc.CBizShpCommercialLogistics odataobj = new AppLogic.DataAlc.CBizShpCommercialLogistics())
            {
                DataSet odata = new Xsd.DataTds.CDmShpCommercialLogistics();
                DataRow drnew = odata.Tables[0].NewRow();
                drnew["LOGISTICS_TEMPLATE_ID"] = odataobj.DataObj.NewID();
                drnew["COMM_TENANT_ID"] = msBsc.SvRef.UserInfo.OperDealerId.Split(',')[0];
                drnew["SEQ_NUM"] = 1;
                //drnew["DELIVER_TYPE_CID"] = "";
                drnew["TEMPLATE_NME"] = this.GetParamHtValue("TEMPLATE_NME");
                odata.Tables[0].Rows.Add(drnew);
                odataobj.Update(odata);

                odataobj.DataObj.ExecuteBySQL(@"	UPDATE A SET
	SEQ_NUM=V1.SEQ_NUM
	FROM  	
	(
		SELECT
		SEQ_NUM=ROW_NUMBER() OVER (PARTITION BY AA.COMM_TENANT_ID ORDER BY AA.LOGISTICS_TEMPLATE_ID ASC)-1
		,AA.LOGISTICS_TEMPLATE_ID 
		FROM SHP_COMMERCIAL_LOGISTICS AA
		WHERE AA.COMM_TENANT_ID='" + msBsc.SvRef.UserInfo.OperDealerId.Split(',')[0] + @"'
	) AS V1 
	LEFT OUTER JOIN SHP_COMMERCIAL_LOGISTICS A ON A.LOGISTICS_TEMPLATE_ID=V1.LOGISTICS_TEMPLATE_ID
");


                this.ExecJScript("layer.msg('成功新增模版！',1,{type:1,shade:false});");
                BoundTempNme(drnew["LOGISTICS_TEMPLATE_ID"].ToString());
            }
        }

        public override void DoAction()
        {
            if (this.strAction == "loadlist")
            {
                loadlist(this.GetParamHtValue("TEMP_ID"));
            }
            else if (this.strAction == "doAddNewTemp")
            {
                doAddNewTemp();
            }
            else if (this.strAction == "doSave")
            {
                doSave();
            }
            else if (this.strAction == "doedit")
            {
                doedit(GetParamHtValue("TEMP_ID"), GetParamHtValue("ZONE_TITLE"));
            }
            else if (this.strAction == "dodelete")
            {
                dodelete(GetParamHtValue("TEMP_ID"), GetParamHtValue("ZONE_TITLE"));
            }
            else if (this.strAction == "dodeleteTemp")
            {
                dodeleteTemp(GetParamHtValue("TEMP_ID"));
            }
            else if (this.strAction == "doAddNew")
            {
                doZoneListSet(GetParamHtValue("TEMP_ID"), "");
                SetContrlValue("txtZoneTitle", "");
                SetContrlValue("txtZONE_TITLE", "");
                SetContrlValue("txtQTY_FIRST", "");
                SetContrlValue("txtPRICE_FIRST", "");
                SetContrlValue("txtQTY_ADD", "");
                SetContrlValue("txtPRICE_ADD", "");
            } 
        }
    }
}